package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.cache.service.IVerifyCodeCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Reference
    private IUserInfoService infoService;
    @Reference
    private IVerifyCodeCacheService verifyCodeCacheService;
    @Reference
    private IUserInfoCacheService userInfoCacheService;

    @RequestMapping("checkPhone")
    @ResponseBody
    public Object checkPhone(String phone){
        boolean result = infoService.checkPhone(phone);
        return result;
    }

    @ResponseBody
    @RequestMapping("sendVerifyCode")
    public Object sendVerifyCode(String phone){
        AjaxResult result = new AjaxResult();
        //判断该手机号是否已经发送有验证码
        String vcode = verifyCodeCacheService.getVerifyCode(phone);
        if(vcode != null){
            return result.mark("验证码已发送,请勿频繁点击");
        }
        //生成短信验证码
        String verifyCode = UUID.randomUUID().toString().substring(0, 4);
        System.err.println("您的验证码是:" + verifyCode);
        //缓存验证码到redis中
        verifyCodeCacheService.setVerifyCode(phone,verifyCode);
        return result;
    }

    @ResponseBody
    @RequestMapping("userRegist")
    public Object userRegist(String verifyCode,String phone,
                             String nickname,String password,String rpassword){
        return infoService.userRegist(verifyCode,phone,nickname,password,rpassword);
    }

    @RequestMapping("userLogin")
    @ResponseBody
    public Object userLogin(String phone, String password,
                            HttpServletResponse response, HttpSession session){

        AjaxResult result = infoService.userLogin(phone, password);

        //登录成功之后,把token通过cookie发送给客户端
        if (result.isSuccess()) {
            String token = (String)result.getData();
            Cookie cookie = new Cookie(Consts.USER_INFO_TOKEN, token);
            cookie.setPath("/");
            response.addCookie(cookie);
            //从缓存中拿到用户对象,存入session
            String user = userInfoCacheService.getUserInfoCache(token);
            session.setAttribute(Consts.USER_INFO, JSON.parseObject(user, UserInfo.class));
        }

        return result;
    }

}
